package org.ajax.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.ajax.dao.GoodsDao;
import org.ajax.dao.impl.GoodsDaoImpl;
import org.ajax.entity.Good;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author CSY
 * @date 2024-11-21
 */
@WebServlet("/update.do")
public class GoodsUpdateServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        String goodId = req.getParameter("goodId");
        String goodName = req.getParameter("goodName");
        String goodPrice = req.getParameter("goodPrice");
        String goodDate = req.getParameter("goodDate");
        String goodStatus = req.getParameter("goodStatus");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        GoodsDao dao = new GoodsDaoImpl();

        Good good = dao.selectGoodById(goodId);
        int n = 0;
        if(good != null){
            try {
                Date gDate = sdf.parse(goodDate);
                good = new Good(goodId, goodName, Double.parseDouble(goodPrice), gDate, Integer.parseInt(goodStatus));
                n = dao.updateGood(good);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        PrintWriter out = resp.getWriter();

        out.println(n);

        out.flush();
        out.close();
    }
}
